<template>
  <div class="editor-header">
    <div class="left">
      <Dropdown :trigger="['click']">
        <div class="menu-item">
          <IconFolderClose /> <span class="text">{{t('message.file')}}</span>
        </div>
        <template #overlay>
          <Menu>
            <MenuItem @click="exportJSON()">{{t('message.exportJson')}}</MenuItem>
            <MenuItem @click="exportPPTX()">{{t('message.exportPptx')}}</MenuItem>
            <MenuItem @click="exportHTML()">{{t('message.exportHtml')}}</MenuItem>
            <MenuItem @click="epubInputVisible = true">{{t('message.exportEpub')}}</MenuItem>


            <hr/>
            <MenuItem @click="selectDoc()">{{t('message.importWord')}}</MenuItem>
            <iframe style='display: none' id='iframe' ref='iframe' src="./docs/index.html" frameborder="0"></iframe>
            <MenuItem @click="selectJSON()">{{t('message.importJson')}}</MenuItem>
                    <input ref="jsonFile" value="" type="file" accept="application/json" id="jsonFile" style='display: none'
               @change="selectJsonFile">
          </Menu>
        </template>
      </Dropdown>
      <Dropdown :trigger="['click']">
        <div class="menu-item"><IconEdit /> <span class="text">{{t('message.edit')}}</span></div>
        <template #overlay>
          <Menu>
            <MenuItem @click="undo()">{{t('message.undo')}}</MenuItem>
            <MenuItem @click="redo()">{{t('message.redo')}}</MenuItem>
            <MenuItem @click="createSlide()">{{t('message.createSlide')}}</MenuItem>
            <MenuItem @click="deleteSlide()">{{t('message.deleteSlide')}}</MenuItem>
            <MenuItem @click="toggleGridLines()">{{
              showGridLines ? t('message.hideGridLines'): t('message.showGridLines')
            }}</MenuItem>
            <MenuItem @click="resetSlides()">{{t('message.resetSlides')}}</MenuItem>
          </Menu>
        </template>
      </Dropdown>
      <Dropdown :trigger="['click']">
        <div class="menu-item"><IconPpt /> <span class="text">{{t('message.demo')}}</span></div>
        <template #overlay>
          <Menu>
            <MenuItem @click="enterScreeningFromStart()">{{t('message.enterScreeningFromStart')}}</MenuItem>
            <MenuItem @click="enterScreening()">{{t('message.enterScreening')}}</MenuItem>
          </Menu>
        </template>
      </Dropdown>
      <Dropdown :trigger="['click']">
        <div class="menu-item">
          <IconHelpcenter /> <span class="text">{{t('message.help')}}</span>
        </div>
        <template #overlay>
          <Menu>
            <!-- <MenuItem @click="goIssues()">意见反馈</MenuItem> -->
            <MenuItem @click="hotkeyDrawerVisible = true">{{t('message.hotkeyDrawerVisible')}}</MenuItem>
          </Menu>
        </template>
      </Dropdown>
    </div>

    <div class="right">
      <Tooltip :mouseLeaveDelay="0" :title="t('message.enterScreening')">
        <div class="menu-item" @click="enterScreening()">
          <IconPpt size="18" fill="#666" style="margin-top: 2px" />
        </div>
      </Tooltip>
      <div class="menu-item">
        <Dropdown>
          <IconAvatar size="18" fill="#666" />
          <template #overlay>
            <Menu style="border: 1px solid #eee">
              <MenuItem v-if="!state.token" @click="loginVisible=true" key="1">
                {{t('message.login')}}
              </MenuItem>
              <MenuItem v-else key="2" @click="exitVisible=true">
                {{t('message.logout')}}
              </MenuItem>
            </Menu>
          </template>
        </Dropdown>
      </div>
      <div class="menu-item">
        <Dropdown>
          <IconSetting size="18" fill="#666" />
          <template #overlay>
            <Menu style="border: 1px solid #eee">
              <MenuItem style="border-bottom: 1px solid #eee" @click="change('zh')" key="1">
                中文
              </MenuItem>
              <MenuItem @click="change('en')" key="2">
                English
              </MenuItem>
            </Menu>
          </template>
        </Dropdown>
      </div>
      <!-- <a href="https://github.com/pipipi-pikachu/PPTist" target="_blank"> -->
      <!-- </a> -->
    </div>
    <Drawer
      width="320"
      placement="right"
      :visible="hotkeyDrawerVisible"
      @close="hotkeyDrawerVisible = false"
    >
      <HotkeyDoc />
    </Drawer>

    <FullscreenSpin :loading="exporting" :tip="t('message.exporting')" />
    <FullscreenSpin :loading="importing" :tip="t('message.importing')" />
    <EpubFiles 
            v-if='epubInputVisible'
            :show="epubInputVisible"
            @close="epubInputVisible = false"
            @insert="src => {epubInputVisible = false }"
          />
    <LoginCom v-if='loginVisible' :show="loginVisible" @close="loginVisible=false"/>
    <Modal 
      v-model:visible="exitVisible" 
      :title="t('message.tips')" 
      @ok="logout"
      :okText="t('message.ok')"
      :cancelText="t('message.cancel')"
    >
    {{t('message.exitInfo')}}
    </Modal>
  </div>
</template>

<script lang="ts">
import {computed, defineComponent, onMounted, ref} from 'vue'
import {MutationTypes, useStore} from '@/store'
import useScreening from '@/hooks/useScreening'
import useSlideHandler from '@/hooks/useSlideHandler'
import useHistorySnapshot from '@/hooks/useHistorySnapshot'
import useExport from '@/hooks/useExport'
import useImport from '@/hooks/useImport'
import EpubFiles from './EpubFiles.vue'
import LoginCom from '../../components/login/index.vue'
import HotkeyDoc from './HotkeyDoc.vue'
import { createRandomCode } from '@/utils/common'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'

export default defineComponent({
  name: 'editor-header',
  components: {
    HotkeyDoc,
    EpubFiles,
    LoginCom,
  },


  setup() {
    const store = useStore()
    const { enterScreening, enterScreeningFromStart } = useScreening()
    const { createSlide, deleteSlide, resetSlides, createSlideByWord } = useSlideHandler()
    const { redo, undo } = useHistorySnapshot()
    const { exporting, exportJSON, exportPPTX, exportHTML } = useExport()
    const { importing, importWORD, importJSON } = useImport()
    const epubInputVisible = ref(false)
    const loginVisible = ref(false)
    const exitVisible = ref(false)
    const { t, locale } = useI18n();
    const showGridLines = computed(() => store.state.showGridLines)
    const toggleGridLines = () => {
      store.commit(MutationTypes.SET_GRID_LINES_STATE, !showGridLines.value)
    }

    const hotkeyDrawerVisible = ref(false)

    const goIssues = () => {
      window.open('https://github.com/pipipi-pikachu/PPTist/issues')
    }
    const iframe = ref<HTMLElement>()
    const isIFrame = (input: HTMLElement | null): input is HTMLIFrameElement =>
     input !== null && input.tagName === 'IFRAME';

    const selectDoc = () => {
      const iframe = document.getElementById('iframe')
      if (isIFrame(iframe) && iframe.contentWindow) {
        iframe.contentWindow.postMessage({data: 'start'}, '*')
      }
    }

    const selectJsonFile = (event: any) => {
      const file = event.target.files[0]
      const reader = new FileReader()
      reader.onload = (loadEvent: any) => {
        const arrayBuffer = loadEvent.target.result
        importJSON(arrayBuffer)
      }
      // reader.readAsArrayBuffer(file)
      reader.readAsText(file)
    }

    const selectJSON = () => {
      const obj = document.getElementById('jsonFile')
      if (obj) {
        obj.click()
      }
    }
    const logout = () => {
      store.dispatch("LogOut", {}).then(res => {
        // console.log(res)
        // if(res.code === 200){
          message.success('退出成功！')
          exitVisible.value = false
        // }
      })
    }

    // 国际化
    const change = (lang: string) => {
      if (locale.value.split('-')[0] == lang) {
        lang=='en'?message.success('Now is English'):message.success('现在已是中文')
        return
      } else {
        locale.value = lang
        localStorage.setItem('lang', lang)
        lang=='en'?message.success('Language changed successfully'):message.success('语言切换成功')
        window.location.reload()
      }
    }

    onMounted(() => {
      window.addEventListener('message', (e) => { 
        if (e.data.newHTML) {
          const strList = e.data.newHTML.split('</p>')
          strList.forEach((element: string, index: Number) => {
            if(index === strList.length-1){
              return
            }
            const obj = {
            content: element + '</p>',
            defaultColor: '#333',
            defaultFontName: 'Microsoft Yahei',
            height: 300,
            id: createRandomCode(),
            left: 15.534491837809457,
            rotate: 0,
            top: 10.94325961032122,
            type: 'text',
            width: 968.9310163243811
          }
            createSlideByWord(obj)
          })
          message.success('导入成功')
        }
      })
    })

    return {
      redo,
      undo,
      showGridLines,
      hotkeyDrawerVisible,
      exporting,
      importing,
      epubInputVisible,
      loginVisible,
      state: store.state,
      exitVisible,
      change,
      locale,
      t,
      logout,
      selectDoc,
      selectJSON,
      selectJsonFile,
      enterScreening,
      enterScreeningFromStart,
      createSlide,
      deleteSlide,
      toggleGridLines,
      createSlideByWord,
      resetSlides,
      exportJSON,
      exportHTML,
      exportPPTX,
      importWORD,
      importJSON,
      goIssues,
      iframe,
    }
  },
})
</script>

<style lang="scss" scoped>
.editor-header {
  background-color: #fff;
  user-select: none;
  border-bottom: 1px solid $borderColor;
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
}
.left,
.right {
  display: flex;
  justify-content: center;
  align-items: center;
}
.menu-item {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  padding: 0 10px;
  transition: background-color $transitionDelay;
  cursor: pointer;

  .text {
    margin-left: 4px;
  }
}

.left .menu-item:hover {
  background-color: $lightGray;
}
</style>